#! -*- coding: utf-8 -*-
from django.shortcuts import render
from rest_framework import viewsets
from rest_framework.views import APIView
from workorder.serializers import *
from workorder.models import FlowConf,ApproveConf
from utils.api_paginator import PageNum
from rest_framework.filters import OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
import json
from workorder.models import *
from user.models import Role,UserRole

from utils.api_paginator import Paginators
from workorder.backends import suborder_approve


class FlowConfViewSet(viewsets.ModelViewSet):
    queryset = FlowConf.objects.all()
    serializer_class = FlowConfSerializer

    # 分页：自定义分页器 覆盖全局配置
    pagination_class = PageNum  # ?page=2&page_size=1

    # 过滤：指定过滤方法类, 排序方法类, 一个或多个
    filter_backends = (DjangoFilterBackend, OrderingFilter)  # 同时支持过滤和排序
    # 指定过滤字段, 不设置, 过滤功能不起效
    filter_fields = ('name',)  # ?username=tom&phone=&is_active=true


    def get_serializer_class(self):
        if self.action == 'list':
            # print(self.action,'走list')
            return FlowConfSerializer
        else:
            # print(self.action, '获取具体数据')
            return FlowConfDeepSerializer


class ApproveConfViewSet(viewsets.ModelViewSet):
    queryset = ApproveConf.objects.all()
    serializer_class = ApproveConfSerializer


class ApprovesView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request):
        data = {
            "count": 36,
            "results":[]
        }
        return Response(data)


class FlowConfInstanceView(APIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request):
        # 1.接收数据
        flowconf_id = request.data.get('flowconf_id')
        parameter = request.data

        # 2.实例化工单
        workorder = WorkOrder.objects.create(
            flowconf_id=flowconf_id,
            create_user=request.user,
            parameter=json.dumps(parameter)
        )

        # 3.实例化子工单
        approve_confs = ApproveConf.objects.filter(flowconf_id=flowconf_id).order_by('sequence')
        for approve in approve_confs:
            mainorder = 'workorder'
            approve_type_id = approve.approve_type_id  # 审批角色类型
            print(request.user, type(request.user))
            approve_user = None
            if approve_type_id == '1':
                approve_user = User.objects.get(id=approve.approve_id)

            approve_user_role = ''
            approve_userrole_id = None
            if approve_type_id == '2':
                approve_userrole_id = approve.approve_id
                approve_user_role = Role.objects.get(id=approve.approve_id).name

            sequence_number = approve.sequence

            action_status = '0'
            suborder_status = '0'
            if sequence_number == 1:
                suborder_status = '1'
            SubOrder.objects.create(
                mainorder=workorder,
                approve_user=approve_user,
                approve_userrole_id=approve_userrole_id,
                approve_user_role=approve_user_role,
                sequence_number=sequence_number,
                approve_type_id=approve_type_id,
                action_status=action_status,
                suborder_status=suborder_status,
            )

        data = {
            "msg":"创建工单完成",
            "results": {
                'workorder_id': workorder.id,
            }
        }
        return Response(data)


class WorkOrderViewSet(viewsets.ModelViewSet):
    queryset = WorkOrder.objects.all()
    serializer_class = WorkOrderSerializer

    def get_serializer_class(self):
        if self.action == 'list':
            # print(self.action,'走list')
            return WorkOrderSerializer
        else:
            return WorkOrderDeepSerializer


class WorkOrderView(APIView):
    queryset = WorkOrder.objects.all()
    serializer_class = WorkOrderSerializer

    def get(self,request):
        self.queryset = self.queryset.all()
        ret = Paginators(self.queryset, request, self.serializer_class)
        return Response(ret.data)


class SubOrderViewSet(viewsets.ModelViewSet):
    queryset = SubOrder.objects.all()
    serializer_class = SubOrderSerializer


class SubOrderListView(APIView):
    queryset = SubOrder.objects.all()
    serializer_class = SubOrderSerializer

    def get(self, request, *args, **kwargs):
        workorder_id = request.GET.get('workorder_id')
        if not workorder_id:
            objs = suborder_approve.user_suborderlist(request)
            print(objs, '999999999999')
            print(request.user.is_superuser,'odddddd')
            if request.user.is_superuser:
                objs = SubOrder.objects.all()
                print(objs, 8888888888888888)
            ret = Paginators(objs, request, self.serializer_class)
            return Response(ret.data)
        else:
            data = {
                'results':{}
            }
            suborder_list = suborder_approve.suborder_detail(request, workorder_id)
            workorder_info = WorkOrder.objects.get(id=workorder_id).parameter
            data['results']['suborder_list'] = suborder_list
            data['results']['workorder_info'] = json.loads(workorder_info)
            return Response(data)


class WorkApproveView(APIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request, *args, **kwargs):
        print(request.data, '99999999999999')
        suborder_approve.handle_suborder_approve(request)
        return Response({})


from opwf import settings
from django.core.paginator import InvalidPage, Paginator
from haystack.forms import ModelSearchForm
from django.http import JsonResponse

# 如果settings.py中配置就是用settings中配置的，否则就每页15条
RESULTS_PER_PAGE = getattr(settings, 'HAYSTACK_SEARCH_RESULTS_PER_PAGE', 15)


def workorder_index_search(request):
    # 1.获取前端传过来的关键字（查询数据）
    query = request.GET.get('q', None)
    page = int(request.GET.get('page', 1))  # 第几页
    page_size = int(request.GET.get('page_size', RESULTS_PER_PAGE))  # 每页多少条

    # 2.获取查询条件，进行查询
    if query:
        form = ModelSearchForm(request.GET, load_all=True)  # 将查询条件传递给查询对象
        if form.is_valid():
            results = form.search()  # 查询出来的最终数据
        else:
            results = []
    else:
        return JsonResponse({"code": 404, "msg": 'No file found！', "data": []})

    # results = results.all().filter(gt__id=1)
    # # ret = results.all().filter(create_user=request.user)
    print(results, 'ooooooooo')
    # print(dir( ret ))
    # results = results.all()[0:2]
    # 3.对结果集进行分页
    paginator = Paginator(results, page_size)
    try:
        page = paginator.page(page)  # 从分好的页中拿第几页
    except InvalidPage:  # 如果分页出错
        return JsonResponse({"code": 404, "msg": 'No file found！', "data": []})

    # 4.把查询的分页结果集对象转换成json格式
    jsondata = []
    for result in page.object_list:  # 分页后的课程查询结果
        data = {
            'id': result.object.id,
            'create_user': result.object.create_user.username,
            'create_ts': result.object.create_ts,
            'order_status': result.object.get_order_status_display(),
            'parameter': result.object.parameter,
        }
        jsondata.append(data)
    result = {
        "code": 200,
        "msg": 'Search successfully！',
        "data": {"count": page.paginator.count, "results": jsondata}
    }
    return JsonResponse(result)


# def suborder_index_search(request):
#     # 1.获取前端传过来的关键字（查询数据）
#     query = request.GET.get('q', None)
#     page = int(request.GET.get('page', 1))  # 第几页
#     page_size = int(request.GET.get('page_size', RESULTS_PER_PAGE))  # 每页多少条
#
#     # 2.获取查询条件，进行查询
#     if query:
#         form = ModelSearchForm(request.GET, load_all=True)  # 将查询条件传递给查询对象
#         if form.is_valid():
#             results = form.search()  # 查询出来的最终数据
#         else:
#             results = []
#     else:
#         return JsonResponse({"code": 404, "msg": 'No file found！', "data": []})
#
#     # 3.对结果集进行分页
#     paginator = Paginator(results, page_size)
#     try:
#         page = paginator.page(page)  # 从分好的页中拿第几页
#     except InvalidPage:  # 如果分页出错
#         return JsonResponse({"code": 404, "msg": 'No file found！', "data": []})
#
#     # 4.把查询的分页结果集对象转换成json格式
#     jsondata = []
#     for result in page.object_list:  # 分页后的课程查询结果
#         approve_user = result.object.approve_user if result.object.approve_user else ''
#         data = {
#             'id': result.object.id,
#             'approve_user': approve_user,
#         }
#         jsondata.append(data)
#     result = {
#         "code": 200,
#         "msg": 'Search successfully！',
#         "data": {"count": page.paginator.count, "results": jsondata}
#     }
#     return JsonResponse(result)